<?php
/**
 * Created by PhpStorm.
 * User: kxy
 * Date: 2019/1/17
 * Time: 下午11:16
 */

namespace App\Http\Controllers\Web\Baike;

use App\Http\Controllers\Controller;
use App\Models\Company\Archive;
use App\Models\Encyclopedia\Article;
use App\Models\Encyclopedia\Category;
use App\Models\System\Region as RegionModel;
use Zhuzhichao\IpLocationZh\Ip;

class DetailController extends Controller
{
    public function detail($id)
    {
        $article = Article::with([
            'category',
            'content',
            'media'
        ])->find($id);

        $ip = Ip::find(request()->ip());
        $city = $ip[2] ?? '';
        $region = '';
        if ($city){
            $region = RegionModel::where('name', $city)->where('level', 2)->first();
        }

        $news = $this->new();

        $relevant = $this->relevant($article);

        $prev = Article::where('id', '<', $id)->orderBy('id', 'desc')->limit(1)->first();

        $next = Article::where('id', '>', $id)->orderBy('id', 'asc')->limit(1)->first();

        $recommend = $this->recommend();

        $category = Category::all();

        $article->media->path = \Storage::url($article->media->path);

        $archive = Archive::with(['region'])
            ->when($region != '', function ($query) use ($region) {
                $query->where('region_id', $region->id);
            })
            ->where('is_state', true)
            ->orderBy('updated_at', 'desc')
            ->take(10)->get();


        return view('baike.details', compact('article', 'prev', 'next', 'news', 'relevant', 'recommend', 'category', 'archive'));
    }

    private function new()
    {
        return Article::take(5)->get();
    }

    private function relevant($article)
    {
        return Article::where('category_id', $article->category_id)->take(5)->get();
    }

    private function recommend()
    {
        return Article::take(8)->get();
    }
}